<?php
/**
 * Created by PhpStorm.
 * User: Mmx
 * Date: 2021\06\07
 * Time: 16:30
 */

namespace app\backend\controller\v5;

use app\backend\validate\DatumValidate;
use app\common\models\Datum as DatumModel;
use app\common\models\Unit as UnitModel;
use app\common\models\DatumCate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\exception\ValidateException;


class Datum extends BaseController
{
    /**
     * 资料列表
     *
     * @return \think\Response
     */
    public function index()
    {
        // 资料库表
        // where条件
        $where1 = input('title');//名称
        $where2 = input('name');//单元名称
        // 分页、排序等
        $page = input('page/d', 1);
        $pageSize = input('pageSize/d', 10);
        $list = DatumModel::field('*')
            ->hasWhere('unit', function ($query) use ($where2) {
                $query->where('title', 'like', '%' . $where2 . '%');
            })
            ->where(function ($query) use ($where1) {
                if ($where1) {
                    $query->where('datum.title', 'like', '%' . $where1 . '%');
                }
            })
            ->order('datum.id', 'desc')
            ->page($page, $pageSize)
            ->select();
//        dd($list);
        $count = DatumModel::count();
        $maxpage = ceil($count / $pageSize);
        foreach ($list as &$value) {
            $value['datum_cate_id'] = $value->datumcate->title;
            unset($value->datumcate);
            $value['unit_id'] = $value->unit->title;
            unset($value->unit);
            $value['video'] = config("app.domain_url") . $value['video'];
        }
        //获取列表
        return sucessMsg(200, '获取成功！', ['list' => $list, 'total' => $count, 'page' => $maxpage]);
    }

    //获取学习中心分类信息
    public function read()
    {
        $model = new DatumCate();
        $data = $model->field('id,title')->select();
        return sucessMsg(200, '获取成功', $data);
    }

    //获取学习中心分类信息
    public function unit()
    {
        $room_id = input('id/d');
        $model = new UnitModel();
        $data = $model->where('room_id', $room_id)->field('id,title')->select();
        return sucessMsg(200, '获取成功', $data);
    }

    //获取信息
    public function edit()
    {
        $id = input('id/d', 0);
        $unit = DatumModel::where('id', $id)->find();
        $room_id = UnitModel::where('id', $unit['unit_id'])->value('room_id');
        return sucessMsg(200, '获取成功', ['unit' => $unit, 'room_id' => $room_id]);
    }

    /**
     * 显示创建轮播表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $model = new DatumModel();
        $data = input();
        try {
            validate(DatumValidate::class)->scene('create')->check($data);
            if ($model->save($data)) {
                return sucessMsg(200, '创建成功！');
            }
            return errMsg(500, '创建失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(400, '请选择要修改的id！');
        }
        $data = input();
        try {
            validate(DatumValidate::class)->scene('update')->check($data);
            if (DatumModel::update($data, ['id' => $id])) {
                return sucessMsg(200, '修改成功！');
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(400, '请选择要删除数据id！');
        }
        $data = DatumModel::find($id);
        if (empty($data)) {
            return errMsg(400, '要删除的数据为空！');
        }
        if (DatumModel::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(500, '删除失败！');
    }

    /**
     * 批量删除
     *
     * @param int $id
     * @return \think\Response
     */
    public function delAll()
    {
        $ids = input('ids/a', 0);
        if (empty($ids)) {
            return errMsg(400, '请选择要删除数据id！');
        }
        $data = DatumModel::find($ids);
        if (empty($data)) {
            return errMsg(400, '要删除的数据为空！');
        }
        if (DatumModel::destroy($ids)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(500, '删除失败！');
    }

    //导入
    public function importExcel()
    {
        // 获取表单上传文件
        $file[] = request()->file();
        if (empty($file[0])) {
            return errMsg(400, '请上传文件！');
        }
        $key = array_keys($file[0]);
        try {
            validate([$key[0] => 'filesize:51200|fileExt:xls,xlsx'])->check($file[0]);
            $savename = \think\facade\Filesystem::putFile('topic', $file[0][$key[0]]);
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $objPHPExcel = $objReader->load(runtime_path() . 'uploads/' . $savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return errMsg(400, '数据不能为空！');
            }
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {
                $data[$j - 2] = [
                    'datum_cate_id' => trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()),
                    'room_id' => trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue()),
                    'unit_id' => trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue()),
                    'title' => trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue()),
                    'English' => trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue()),
                    'American' => trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()),
                    'desc' => trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue()),
                    'example' => trim($objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue()),
                    'translate' => trim($objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue()),
                    'else' => trim($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue()),
                ];
            }
            // 创建一个新数组
            $createData = [];
            // 循环数据
            foreach ($data as $k => &$v) {
                if (empty($v['datum_cate_id'])) {
                    unset($v);
                } elseif (empty($v['room_id'])) {
                    unset($v);
                } elseif (empty($v['unit_id'])) {
                    unset($v);
                } elseif (empty($v['title'])) {
                    unset($v);
                } elseif (empty($v['English'])) {
                    unset($v);
                } elseif (empty($v['American'])) {
                    unset($v);
                } elseif (empty($v['desc'])) {
                    unset($v);
                } elseif (empty($v['example'])) {
                    unset($v);
                } elseif (empty($v['translate'])) {
                    unset($v);
                } elseif (empty($v['else'])) {
                    unset($v);
                }
                $cate = DatumCate::where('title', $v['datum_cate_id'])->find();
                $room = \app\common\models\Room::where('title', $v['room_id'])->find();
                $unit = \app\common\models\Unit::where(['title' => $v['unit_id'], 'room_id' => $room['id']])->find();
                if (empty($cate) || empty($unit)) {
                    unset($v);
                    return errMsg(400, '请重新核对数据...');
                }
                $v['datum_cate_id'] = $cate['id'];
                $v['unit_id'] = $unit['id'];
                unset($v['room_id']);
            }
            $createData = $data;
            $model = new DatumModel();
            if ($model->saveAll($createData)) {
                return sucessMsg(200, '导入成功！');
            }
            return errMsg(500, '导入失败！');
        } catch (\think\exception\ValidateException $e) {
            return errMsg(422, $e->getMessage());
        }


    }
}